<template>
  <div class="login-container">
    <el-col :xs="24" :sm="{span: 12, offset: 6}" :md="{span: 6, offset: 9}">
      <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left" label-width="0px"
        class="card-box login-form">
        <el-col class="login_top">欢迎使用 管理系统
          <span bg1></span>
          <span bg2></span>
        </el-col>
        <el-col class="center">
          <el-form-item prop="username">
            <span class="svg-container svg-container_login">
              <svg-icon icon-class="user" />
            </span>
            <el-input name="username" type="text" v-model="loginForm.username" autoComplete="on" placeholder="用户名" clearable />
          </el-form-item>
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password"></svg-icon>
            </span>
            <el-input name="password" :type="pwdType" @keyup.enter.native="handleLogin" v-model="loginForm.password" autoComplete="on"
              placeholder="密码" clearable></el-input>
              <span class="show-pwd" @click="showPwd"><svg-icon icon-class="eye" /></span>
          </el-form-item>
          <el-col>
            <el-checkbox v-model="checked" style="margin-left: 15px;">记住密码</el-checkbox>
            <i tip>一周有效</i>
          </el-col>
          <el-button class='login_btn' :loading="loading" @click.native.prevent="handleLogin">立即登录</el-button>
          <el-form-item>
          </el-form-item>
        </el-col>
      </el-form>
      <!-- 验证-模块 -->
      <el-row v-if="isShow">
        <vue-verify :type="5" :style="verifyStyle" :imgUrl="defImg" :imgName="['']"
          :imgSize="{width:'100%', height:'150px'}" :barSize="{width:'100%', height:'40px'}" :defaultNum="5"
          @success="verifyHandle(true)" :showButton="false"></vue-verify>
        <div class="slide-verify-mark" @click="isShow=false"></div>
      </el-row>
    </el-col>
  </div>
</template>

<script>
import { isvalidUsername } from '@/utils/validate'
import { defImg } from '@/utils' // 获取背景图
import * as commUtil from '@/utils/commUtil' // 通用工具
import { msgB } from '@/utils/message'
import md5 from 'js-md5'
import Fingerprint2 from 'fingerprintjs2'
import verify from 'vue2-verify' // 验证器-vue-  type: 1 常规验证码 2 算数 3 滑动 4 滑动拼图 5 选择汉字
export default {
  name: 'login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        // admin 支付后台 merchant 商户后台
        username: '', password: '', type: 'merchant', deviceId: ''
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      loading: false, c_key: '_log_use_', // 记住密码cookie-key
      pwdType: 'password', checked: false, // 记住密码
      // 验证
      isVerify: false, isShow: false, defImg: defImg()
    }
  },
  computed: {
    verifyStyle() { // 验证器style
      const w = /mobile/i.test(navigator.userAgent) ? '100%' : '400px'
      const str = `position: fixed;z-index: 1000;left: 50%;top: 50%;` +
      `transform: translate(-50%,-50%);width:${w};`
      // `transform: translate(-50%,-50%);background: #fff;` +
      // `border-radius: 10px;padding: 15px 15px 50px;`
      return str
    }
  },
  components: { vueVerify: verify },
  created() {
    // 获取设备唯一码
    this.getBrowseId()
    // 初始化--config.json
    this.init()
  },
  mounted() { // dom加载完
    const cookieVal = this.$cookie.get(this.c_key)
    if (cookieVal) {
      const deVal = commUtil.deCode(cookieVal)
      const arrVal = deVal.split(',')
      this.loginForm.username = arrVal[0]
      this.loginForm.password = arrVal[1]
    }
  },
  methods: {
    init() {
      this.$axios.get('./static/config/conf.json').then(res => {
        if (res.status == 200 && res.data) {
          // console.log(res.data)
          this.$store.commit('ALL_CONF', res.data)
          // this.loginForm.channelId = res.data.CHANNEL_ID
        }
      })
    },
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    // 验证成功
    verifyHandle(bool) {
      if (bool) {
        this.isVerify = true
        this.isShow = false
        this.$message({ message: '验证成功!', type: 'success' })
        this.handleLogin() // 提交
      } else {
        this.$message({ message: '验证失败!', type: 'warning' })
      }
    },
    handleLogin() {
      const openValid = process.env.VUE_APP_LOGIN_VALID // 是否-启动验证
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          if (!this.isVerify & openValid) { // 验证没有通过
            if (!this.isShow) {
              this.isShow = true
            }
            this.$message({ message: '您还没有通过验证，请验证成功后再提交！', type: 'warning' })
            return
          }
          this.loading = true
          this.$store.dispatch('Login', this.loginForm).then(res => {
            this.isVerify = false // 清除验证
            this.loading = false
            if (res.status == 0) {
              // 跳转
              this.checkedPwd() // 记住密码
              this.$router.push({ path: '/' })
            } else {
              // 消息提示
              msgB(res.message, 'error')
            }
          }).catch(() => {
            this.loading = false
            this.isVerify = false
          })
        } else {
          console.log('error submit!!')
          this.isVerify = false
          return false
        }
      })
    },
    // 获取浏览器指纹-唯一码
    getBrowseId() {
      const this_ = this
      new Fingerprint2({
        // 配置项（可选）
        excludeSessionStorage: true, // 排除会话存储用户的浏览器支持
        excludeOpenDatabase: true, // 排除式用户浏览器的支持
        excludeIndexedDB: true, // 排除IndexedDB用户浏览器的支持
        excludeLanguage: true, // 排除浏览器的语言
        excludeJsFonts: true,
        excludeDeviceMemory: true,
        excludeAdBlock: true,
        userAgent: true // 用户代理，包含浏览器版本号
      }).get(function (result, components) {
        // console.log('浏览器指纹码: %s', result)
        console.log('浏览器指纹码(md5): %s', md5(result))
        // console.log(JSON.stringify(components))
        // console.log('浏览器指纹码(手md5): %s', md5(JSON.stringify(components)))
        this_.loginForm.deviceId = md5(result)
      })
    },
     // 记住密码
    checkedPwd() {
      if (this.checked) {
        const enVal = commUtil.enCode(`${this.loginForm.username},${this.loginForm.password}`)
        this.$cookie.set(this.c_key, enVal, {expires: 7}) // 7天
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg: #f3f3f4;
$dark_gray: #889aa4;
$light_gray: #e6e6e6;
$input_: #000;
$btn_: #1ab394;
$btn_h: #18a689;
$bg_img: '~/static/img/login.jpg';

.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  // background-color: $bg;
  background: url($bg_img) 0% 0% / cover no-repeat;
  &>div{position: relative;}
  // top
  .login_top {
    height: 117px;
    background-color: #0371d1;
    border-radius: 12px 12px 0 0;
    font-size: 30px;
    font-weight: 400;
    font-stretch: normal;
    letter-spacing: 0;
    color: #fff;
    line-height: 117px;
    text-align: center;
    overflow: hidden;
    -webkit-transform: rotate(0);
    -moz-transform: rotate(0);
    -ms-transform: rotate(0);
    -o-transform: rotate(0);
    transform: rotate(0);
    span{
      display: inline-block;
      width: 74px;
      height: 74px;
      background: #fff;
      opacity: .1;
      position: absolute;
      &[bg1]{
        left: 0;
        top: 43px;
        border-radius: 0 74px 0 0;
      }
      &[bg2]{
        right: -5px;
        top: -10px;
        border-radius: 35px;
      }
    }
  }
  // 内容
  .center {
    background: #fff;
    border-radius: 0 0 12px 12px;
    padding: 40px 40px 53px;
  }
  // 提示
  [tip] {
    float: right;
    margin-right: 5px;
    color: #a59b9b;
    font-size: 10px;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
    &_login {
      font-size: 20px;
    }
  }
  .title {
    color: $light_gray;
    font-size: 180px;
    font-weight: 800;
    letter-spacing: -10px;
    margin: 0 auto;
    text-align: center;
  }
  .title2 {
    margin-top: 5px;
    font-weight: 600;
    text-align: center;
  }
  .login-form {
    margin-top: 30%;
    padding: 35px 35px 15px 35px;
    input:-webkit-autofill {
      -webkit-box-shadow: 0 0 0px 1000px #293444 inset !important;
      -webkit-text-fill-color: #fff !important;
    }
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $input_;
      height: 47px;
    }
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;
    }
  }
  .el-form-item {
    border-bottom: 1px solid #dae1e6;
    // border: 1px solid rgba(255, 255, 255, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
  .thirdparty-button {
    position: absolute;
    right: 35px;
    bottom: 28px;
  }
  .login_btn {
    width: 100%;
    color: #FFF;
    margin-top: 10px;
    border-radius: 15px;
    background: #0371d1;
    border-color: #409EFF;
    &:hover {
      background: #2980dc;
      border-color: #66b1ff;
    }
  }
  .tips {
    color: #454545;
  }
}
// 遮罩
.slide-verify-mark {
  position: fixed;
  left: 0;
  top: 0;
  opacity: 0.5;
  width: 100%;
  height: 100%;
  background: #000;
  z-index: 998;
}
</style>
